<?php
namespace manage;

require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/Lib/Page.php';

global $config_item;

use Workerman\Protocols\Http;
if(!Http::sessionStarted()) Http::sessionStart();
checkLogin();
// 权限检查
$funcs = getFuncs($_SESSION['admin_group']);
if(!in_array(33, $funcs)) {
	echo '<script type="text/javascript">location.href="dashboard.php";</script>';
	#Http::header('Location:dashboard.php');
	return;
}

$error = $_GET['error'] ?? null;
$success = $_GET['success'] ?? null;
$now = time();
$today = date('Y-m-d');

global $game_redis;
global $OPERATION_EXCHANGE, $OPERATION_ITEM;

$ticket_kc = KEY['StockTicket'];
$integral_kc = KEY['StockIntegral'];
$gold_kc = KEY['StockGold'];

$action = $_GET['action'] ?? null;
if($action == 'init_ticket_stock') {
	if(!in_array(34, $funcs)) {
		header('location:game_stock.php?error="没有操作权限"');
		return;
	}
	$sets = [];
	foreach($OPERATION_EXCHANGE['ticket'] as $v) {
		$sets[$v['Id']] = $v['Stock'];
	}
	if(!empty($sets)) {
		\Core\Cache::hmset($ticket_kc['instance'], $ticket_kc['pre'], $sets);
		echo '<script>location.href="game_stock.php?success=初始化奖券兑换库存成功";</script>';
		return;
	}
}
else if($action == 'init_integral_stock') {
	if(!in_array(34, $funcs)) {
		header('location:game_stock.php?error="没有操作权限"');
		return;
	}
	$sets = [];
	foreach($OPERATION_EXCHANGE['integral'] as $v) {
		$sets[$v['Id']] = $v['Stock'];
	}
	if(!empty($sets)) {
		\Core\Cache::hmset($integral_kc['instance'], $integral_kc['pre'], $sets);
		echo '<script>location.href="game_stock.php?success=初始化积分兑换库存成功";</script>';
		return;
	}
}
else if($action == 'edit_ticket_store'){
    $param = $_POST;
    if (!isset($param['id']) || $param['id'] == null || $param['id'] < 1){
        echo json_encode(['code'=>0,'msg'=>'参数有误']);return;
    }
    \Core\Cache::hset($ticket_kc['instance'],$ticket_kc['pre'],$param['id'],(int)$param['stock']);
    echo json_encode(['code'=>1,'msg'=>'已修改']);return;
}
else if($action == 'edit_integral_store'){
    $param = $_POST;
    if (!isset($param['id']) || $param['id'] == null || $param['id'] < 1){
        echo json_encode(['code'=>0,'msg'=>'参数有误']);return;
    }
    \Core\Cache::hset($integral_kc['instance'],$integral_kc['pre'],$param['id'],(int)$param['stock']);
    echo json_encode(['code'=>1,'msg'=>'已修改']);return;
}
else if($action == 'edit_gold_store'){
    $param = $_POST;
    if (!isset($param['id']) || $param['id'] == null || $param['id'] < 1){
        echo json_encode(['code'=>0,'msg'=>'参数有误']);return;
    }
    \Core\Cache::hset($gold_kc['instance'],$gold_kc['pre'],$param['id'],(int)$param['stock']);
    echo json_encode(['code'=>1,'msg'=>'已修改']);return;
}

$stock_ticket = \Core\Cache::hgetall($ticket_kc['instance'], $ticket_kc['pre']);
$stock_integral = \Core\Cache::hgetall($integral_kc['instance'], $integral_kc['pre']);
$stock_gold = \Core\Cache::hgetall($gold_kc['instance'], $gold_kc['pre']);

display_header();

?>

<section class="content" style="">

	<?php display_title('游戏管理 - 库存管理'); ?>

	<?php if($error) : ?>
		<div class="alert alert-warning alert-dismissible">
			<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
			<span><?php echo $error; ?></span>
		</div>
	<?php endif ?>
	<?php if($success) : ?>
		<div class="alert alert-success alert-dismissible">
			<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
			<h4><i class="icon fa fa-check"></i> 成功</h4>
			<?php echo $success; ?>
		</div>
	<?php endif ?>

	<div class="box box-primary" style="margin-top:5px;">
		<div class="box-header with-border" header_name="game_info">
			<div class="col-sm-6 tt" style="font-size:18px;text-align:left;padding-left:0;">
				<i class="fa fa-ticket"></i> 奖券兑奖库存
			</div>
			<div style="text-align:right">
				<button class="btn btn-danger" onclick="if(confirm('确定初始化所有奖券库存到初始值吗?')) { location.href='game_stock.php?action=init_ticket_stock'; }">初始化库存</button> |
				<button class="btn btn-primary" onclick="location.href='player_exchange.php';">查看兑换记录</button>
			</div>
		</div>
		<div class="box-body">
			<table class="table table-bordered table-striped dataTable table-hover ticketToStock" role="grid" aria-describedby="example1_info">
				<tr>
					<th width="200">兑换商品 * 数量</th>
					<th width="300">兑换条件</th>
					<th width="100">基础库存</th>
					<th width="100">当前库存</th>
					<th>操作</th>
				</tr>
				<?php
					global $OPERATION_EXCHANGE, $OPERATION_ITEM;
					foreach($OPERATION_EXCHANGE['ticket'] as $info) {
						echo '<tr><td>' . $info['ItemName'] . '*' . $info['ExchangeNum'] . '</td>';
						echo '<td>' . $OPERATION_ITEM[$info['ItemId1']]['name'] .'*'. $info['ItemNum1'];
						if($info['ItemId2'] && $info['ItemNum2'] > 0) {
							echo '<br />' . $OPERATION_ITEM[$info['ItemId2']]['name'] .'*'. $info['ItemNum2'];
						}
						echo '</td>';
						echo '<td>'.$info['Stock'].'</td>';
						echo '<td>' . ($stock_ticket[$info['Id']] ?? '-') . '</td>';
				?>
                    <td>
                        <button data-id="<?php echo $info['Id'];?>" data-title="<?php echo $info['ItemName'] . '*' . $info['ExchangeNum'];?>" class="btn btn-xs btn-info">修改库存</button>
                    </td>
                <?php
						echo '</tr>';
					}
				?>
			</table>
		</div>
	</div>

    <div class="box box-primary" style="margin-top:5px;">
        <div class="box-header with-border" header_name="game_info">
            <div class="col-sm-6 tt" style="font-size:18px;text-align:left;padding-left:0;">
                <i class="fa fa-ticket"></i> 金币兑奖库存
            </div>
            <div style="text-align:right">
                <!--                <button class="btn btn-danger" onclick="if(confirm('确定初始化所有奖券库存到初始值吗?')) { location.href='game_stock.php?action=init_ticket_stock'; }">初始化库存</button> |-->
                <!--                <button class="btn btn-primary" onclick="location.href='player_exchange.php';">查看兑换记录</button>-->
            </div>
        </div>
        <div class="box-body">
            <table class="table table-bordered table-striped dataTable table-hover goldToStock" role="grid" aria-describedby="example1_info">
                <tr>
                    <th width="200">兑换商品 * 数量</th>
                    <th width="300">兑换条件</th>
                    <th width="100">基础库存</th>
                    <th width="100">当前库存</th>
                    <th>操作</th>
                </tr>
                <?php
                global $OPERATION_EXCHANGE, $OPERATION_ITEM;
                foreach($OPERATION_EXCHANGE['skill'] as $info) {
                    echo '<tr><td>' . $info['ItemName'] . '*' . $info['ExchangeNum'] . '</td>';
                    echo '<td>' . $OPERATION_ITEM[$info['ItemId1']]['name'] .'*'. $info['ItemNum1'];
                    if($info['ItemId2'] && $info['ItemNum2'] > 0) {
                        echo '<br />' . $OPERATION_ITEM[$info['ItemId2']]['name'] .'*'. $info['ItemNum2'];
                    }
                    echo '</td>';
                    echo '<td>'.$info['Stock'].'</td>';
                    echo '<td>' . ($stock_gold[$info['Id']] ?? '-') . '</td>';
                    ?>
                    <td>
                        <button data-id="<?php echo $info['Id'];?>" data-title="<?php echo $info['ItemName'] . '*' . $info['ExchangeNum'];?>" class="btn btn-xs btn-info">修改库存</button>
                    </td>
                    <?php
                    echo '</tr>';
                }
                ?>
            </table>
        </div>
    </div>

	<div class="box box-info" style="margin-top:15px;">
		<div class="box-header with-border" header_name="game_info">
			<div class="col-sm-6 tt" style="font-size:18px;text-align:left;padding-left:0;">
				<i class="fa fa-star-o"></i> 积分兑换库存
			</div>
			<div style="text-align:right">
				<button class="btn btn-danger" onclick="if(confirm('确定初始化所有积分兑换库存到初始值吗?')) { location.href='game_stock.php?action=init_integral_stock'; }">初始化库存</button>
			</div>
		</div>
		<div class="box-body">
			<table class="table table-bordered table-striped dataTable table-hover integralToStock" role="grid" aria-describedby="example1_info">
				<tr>
					<th width="200">兑换商品 * 数量</th>
					<th width="300">兑换条件</th>
					<th width="100">基础库存</th>
					<th width="100">当前库存</th>
					<th>操作</th>
				</tr>
				<?php
				foreach($OPERATION_EXCHANGE['integral'] as $id => $info) {
					echo '<tr><td>' . $info['ItemName'] . '*' . $info['ExchangeNum'] . '</td>';
					echo '<td>' . $OPERATION_ITEM[$info['ItemId1']]['name'] .'*'. $info['ItemNum1'];
					if($info['ItemId2'] && $info['ItemNum2'] > 0) {
						echo ' + ' . $OPERATION_ITEM[$info['ItemId2']]['name'] .'*'. $info['ItemNum2'];
					}
					echo '</td>';
					echo '<td>'.$info['Stock'].'</td>';
					echo '<td>' . ($stock_integral[$info['Id']] ?? '-') . '</td>';?>
                    <td>
                        <button data-id="<?php echo $info['Id'];?>" data-title="<?php echo $info['ItemName'] . '*' . $info['ExchangeNum'];?>" class="btn btn-xs btn-info">修改库存</button>
                    </td>
                    </tr>
                <?php } ?>
			</table>
		</div>
	</div>

</section>

<!-- jQuery 3 -->
<script src="http://gold-static.91changwan.com/web/manage_static/js/jquery.min.js"></script>
<script src="http://gold-static.91changwan.com/web/manage_static/js/jquery.cookie.js"></script>
<script src="http://gold-static.91changwan.com/web/manage_static/js/jquery.pjax.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="http://gold-static.91changwan.com/web/manage_static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="http://gold-static.91changwan.com/web/manage_static/bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="http://gold-static.91changwan.com/web/manage_static/plugins/input-mask/jquery.inputmask.js"></script>
<script src="http://gold-static.91changwan.com/web/manage_static/plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="http://gold-static.91changwan.com/web/manage_static/plugins/input-mask/jquery.inputmask.extensions.js"></script>
<!-- date-range-picker -->
<script src="http://gold-static.91changwan.com/web/manage_static/bower_components/moment/min/moment.min.js"></script>
<script src="http://gold-static.91changwan.com/web/manage_static/bower_components/bootstrap-daterangepicker/daterangepicker.js"></script>
<!-- bootstrap datepicker -->
<script src="http://gold-static.91changwan.com/web/manage_static/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
<!-- bootstrap time picker -->
<script src="http://gold-static.91changwan.com/web/manage_static/plugins/timepicker/bootstrap-timepicker.min.js"></script>
<!-- SlimScroll -->
<script src="http://gold-static.91changwan.com/web/manage_static/bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- iCheck 1.0.1 -->
<script src="http://gold-static.91changwan.com/web/manage_static/plugins/iCheck/icheck.min.js"></script>
<!-- FastClick -->
<script src="http://gold-static.91changwan.com/web/manage_static/bower_components/fastclick/lib/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="http://gold-static.91changwan.com/web/manage_static/dist/js/adminlte.min.js"></script>
<!-- layer -->
<script src="plugins/layer/layer.js"></script>
<script type="text/javascript">
    $(function() {
        // 修改道具数量
        $('#click_add_item').click(function() {
            var _num = $('#modal_item_num').val().trim();
            if(!_num || isNaN(_num) || _num <= 0) {
                alert('错误的数字'); return false;
            }
            var _this = this;
            var _type = $("input[name='change_item_type']:checked").val();
            var _uid = $('#current_uid').val();
            var _itemid = $('#change_item_id').val();
            $.ajax({
                url: 'player_action.php?action=change_item&type='+_type+'&num='+_num+'&uid='+_uid+'&itemid='+_itemid,
                beforeSend: function() {
                    $(_this).hide();
                    $(_this).parent().append('<span class="load"><img src="dist/img/ajax-loader.gif" /> ...</span>');
                },
                success: function(data) {
                    if(data == 'OK') {
                        alert('修改成功');
                        location.reload();
                    }
                    else {
                        if(data == 'AUTH') alert('无权限,无法修改');
                        else alert('修改失败' + ' - ' + data);
                    }
                    $(_this).parent().find('.load').remove();
                    $(_this).show();
                }
            });
        });
        $('#modal-edit-item').on('hidden.bs.modal', function (e) { $('#modal_item_num').val(0); });

        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);

        //奖券兑奖库存修改
        $('.ticketToStock').find('.btn-info').on('click',function () {
            var objId = $(this).data('id')
                ,title = $(this).data('title');
            layer.prompt({title: '请输入`'+ title +'`新库存', formType: 0}, function(text, index){
                if (isNaN(text)) {
                    layer.msg('请输入正整数!',{icon:5,time:3000});
                    return;
                }
                $.post('game_stock.php?action=edit_ticket_store',{id:objId,stock:text},function (res) {
                    if (res.code < 1) {
                        layer.msg(res.msg,{icon:5,time:3000});
                        return;
                    } else {
                        layer.msg(res.msg,{icon:1,time:3000},function () {
                            layer.close(index);
                            window.location.reload();
                        });
                    }
                },'json');
            });
        });

        //积分兑奖库存修改
        $('.integralToStock').find('.btn-info').on('click',function () {
            var objId = $(this).data('id')
                ,title = $(this).data('title');
            layer.prompt({title: '请输入`'+ title +'`新库存', formType: 0}, function(text, index){
                if (isNaN(text)) {
                    layer.msg('请输入正整数!',{icon:5,time:3000});
                    return;
                }
                $.post('game_stock.php?action=edit_integral_store',{id:objId,stock:text},function (res) {
                    if (res.code < 1) {
                        layer.msg(res.msg,{icon:5,time:3000});
                        return;
                    } else {
                        layer.msg(res.msg,{icon:1,time:3000},function () {
                            layer.close(index);
                            window.location.reload();
                        });
                    }
                },'json');
            });
        })

        //金币兑奖库存修改
        $('.goldToStock').find('.btn-info').on('click',function () {
            var objId = $(this).data('id')
                ,title = $(this).data('title');
            layer.prompt({title: '请输入`'+ title +'`新库存', formType: 0}, function(text, index){
                if (isNaN(text)) {
                    layer.msg('请输入正整数!',{icon:5,time:3000});
                    return;
                }
                $.post('game_stock.php?action=edit_gold_store',{id:objId,stock:text},function (res) {
                    if (res.code < 1) {
                        layer.msg(res.msg,{icon:5,time:3000});
                        return;
                    } else {
                        layer.msg(res.msg,{icon:1,time:3000},function () {
                            layer.close(index);
                            window.location.reload();
                        });
                    }
                },'json');
            });
        })
    });
</script>

</body>
</html>

